package com.example.opengldemo;

import android.opengl.GLES20;
import android.util.Log;

public class ShaderHelper {

    public static int compileShader(int type,String shaderCode){

        int shaderObjectId = GLES20.glCreateShader(type);

        if(shaderObjectId==0){
            Log.e("androidLog","Could not create new shader");
            return 0;
        }
        GLES20.glShaderSource(shaderObjectId,shaderCode);
        GLES20.glCompileShader(shaderObjectId);

        int []compileStatus = new int[1];
        GLES20.glGetShaderiv(shaderObjectId,GLES20.GL_COMPILE_STATUS,compileStatus,0);

        Log.e("androidLog","Results of compiling source:"+"\n"+shaderCode+"\n"+GLES20.glGetShaderInfoLog(shaderObjectId));
        if(compileStatus[0]==0){
            GLES20.glDeleteShader(shaderObjectId);
            Log.e("androidLog","Compilation of shader failed");
        }
        return shaderObjectId;
    }


    public static int linkProgram(int vertexShaderId,int fragmentShaderId){

        int programObjectId = GLES20.glCreateProgram();
        if(programObjectId==0){
            Log.e("androidLog","Could not create new program");
            return 0;
        }

        GLES20.glAttachShader(programObjectId,vertexShaderId);
        GLES20.glAttachShader(programObjectId,fragmentShaderId);

        GLES20.glLinkProgram(programObjectId);

        int linkStatus[] = new int[1];
        GLES20.glGetProgramiv(programObjectId,GLES20.GL_LINK_STATUS,linkStatus,0);
        if(linkStatus[0]==0){
            Log.e("androidLog","Could not linking Program");
            return 0;
        }
        Log.e("androidLog","Results of linking program: "+GLES20.glGetProgramInfoLog(programObjectId));
        return programObjectId;
    }

    public static boolean validateProgram(int programObjectId){

        GLES20.glValidateProgram(programObjectId);

        int valiedateStatus[] = new int[1];

        GLES20.glGetProgramiv(programObjectId,GLES20.GL_VALIDATE_STATUS,valiedateStatus,0);

        Log.e("androidLog","Results of validating program:"+valiedateStatus[0]+"\nLog:"+GLES20.glGetProgramInfoLog(programObjectId));

        return valiedateStatus[0]!=0;
    }

    public static int buildProgram(String vertexShaderSource,String fragmentShaderSource){

        int vertexShader = compileShader(GLES20.GL_VERTEX_SHADER,vertexShaderSource);
        int fragmentShader = compileShader(GLES20.GL_FRAGMENT_SHADER,fragmentShaderSource);

        int program = linkProgram(vertexShader,fragmentShader);

        validateProgram(program);

        return program;
    }

}
